﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BizElements.Core
{
    internal static class ArrayUtil
    {
        internal static bool IsNullOrEmpty(IEnumerable collection)
        {
            if (collection == null)
                return true;

            IEnumerator enumerator = collection.GetEnumerator();
            bool isEmpty = !enumerator.MoveNext();
            return isEmpty;
        }

        internal static int Count(IEnumerable collection)
        {
            if (collection is ICollection)
                return (collection as ICollection).Count;

            int count = 0;
            foreach (object item in collection)
                count++;

            return count;
        }

        internal static T[] ToArray<T>(IEnumerable collection, string propertyName)
        {
            List<T> output = new List<T>();
            PropertyInfo property = null;
            foreach (object item in collection)
            {
                if (property == null)
                    property = item.GetType().GetProperty(propertyName);

                output.Add((T)property.GetValue(item, null));
            }

            return output.ToArray<T>();
        }

        internal static TList GetDifference<TList, TElement>(IEnumerable source, TElement[] valuesToRemove)
            where TList : IList, new()
        {
            TList difference = new TList();
            foreach (TElement element in source)
            {
                bool survives = (Array.IndexOf<TElement>(valuesToRemove, element) < 0);
                if (survives)
                    difference.Add(element);
            }

            return difference;
        }
    }
}